<?php
class Mageex_AdvanceSeo_Model_Observer 
{
	 /**
     * Enable/disable configuration
     */
    const XML_PATH_GENERATION_ENABLED = 'mageex_advanceseo/rewritedata/enable';

    /**
     * Cronjob expression configuration
     */
    const XML_PATH_CRON_EXPR = 'crontab/jobs/advanceseo_rewritedata/schedule/cron_expr';
	
	
	public function rewriteUrl(Varien_Event_Observer $observer)
	{
		if(Mage::helper('advanceseo/config')->isEnableRewriteSearch()){
			$pathInfo = pathinfo($_SERVER['PHP_SELF']);
			if($pathInfo['basename'] == 'result'){
				$front 		= $observer->getEvent()->getFront();
				$origUri 	= parse_url($front->getRequest()->getRequestUri());
				$uri 		= trim($origUri['query'], 'q=');
				if(!isset($origUri['query'])) return false;
				if(!isset($origUri['path'])) return false;
				if(preg_match('#(\?|&)q=(.*)#',$url['query'])) return false;
				
				$suffix = Mage::helper('advanceseo/config')->getPathSearch();
				$char 	= Mage::getStoreConfig('catalog/seo/title_separator');

				$uri = preg_replace('/\+/', $char, $uri);
				$url = Mage::getBaseUrl() 
							. $suffix . '/' 
							. $uri.Mage::helper('advanceseo/data')->getSuffix(); 
			   $front->getResponse()
					->setRedirect($url) 
					->setHttpResponseCode(301)
					->sendResponse();
				exit;
			}
		}
	}
	
	public function scheduledCron($schedule)
	{
		if (!Mage::getStoreConfigFlag(self::XML_PATH_GENERATION_ENABLED, Mage::app()->getStore()->getId())) {
            return;
        }	
		try{
			$obj = Mage::getModel('advanceseo/old');
			$status = $obj->rewriteData();
		}catch(Exception $e){
				Mage::log($e->getMessage());
		}
		
		if($status){
			return;
		}
	}
	public function sitemapSubmitCron()
	{
		if(!Mage::helper('advanceseo/sitemap')->isEnableSubmit()){
			return;
		}
		$sitemaps = Mage::getModel('sitemap/sitemap')->getCollection();
		foreach($sitemaps as $sitemap){
			try{
				$obj = Mage::getModel('advanceseo/submit');
				$msg = $obj->submit($sitemap->getId());	
				Mage::log($msg);
			}catch(Exception $e){
				Mage::log($e->getMessage());
			}
		}
		
	}
	public function submit($observer) 
	{
		if (Mage::helper('advanceseo/sitemap')->isEnabled() && 
			Mage::helper('advanceseo/sitemap')->isAutoSubmit()) {
			try {
				Mage::log("Sitemap regeneration detected - auto running submission");
				$id = $observer->getEvent()->getSitemap()->getId();
				$obj = Mage::getModel('advanceseo/submit');
				$msg = $obj->submit($id);	
				Mage::log($msg);		
			} catch (Exception $e) {
				Mage::log($e->getMessage());
			}
			return;
		} 
	}
	
	public function registerProductId(Varien_Event_Observer $observer)
    {
        $product = $observer->getEvent()->getProduct();
        Mage::unregister('advanceseo_product_id');
        Mage::register('advanceseo_product_id', $product->getId());
    }
}